import random
import config
from config import 随机数范围
from win32api import GetMonitorInfo, MonitorFromPoint
import time
import ctypes
import _thread
import time
import base64  # for uncoder the str or int
import requests


def loading(lock):
    chars = ["⣾", "⣷", "⣯", "⣟", "⡿", "⢿", "⣻", "⣽"]
    i = 0
    print("")
    while lock[0]:
        i = (i + 1) % len(chars)
        print("\033[A%s %s" % (chars[i], lock[1] or "" if len(lock) >= 2 else ""))
        time.sleep(0.25)
    print("")


lock = [True, ""]
try:
    _thread.start_new_thread(loading, (lock,))
except Exception as e:
    print(e)

lock[1] = "正在读取配置..."
time.sleep(0.5)
lock[1] = "正在加载主窗口..."
time.sleep(1)
lock[1] = "正在加载抽号窗口..."
time.sleep(0.85)
lock[1] = "正在启动.............."
time.sleep(3)
lock[1] = "请稍等..."
lock[0] = False
time.sleep(0.5)
print(
    """
欢迎使用!"""
)
# 告诉操作系统使用程序自身的dpi适配
ctypes.windll.shcore.SetProcessDpiAwareness(1)
# 获取屏幕的缩放因子
ScaleFactor = ctypes.windll.shcore.GetScaleFactorForDevice(0)
# 设置程序缩放

# code by 2409

import tkinter as tk
from cgitb import text

######################################################

分支 = "master"
ver = "v0.9"
verdate = "20230503"
debug = True


print("版本", ver, ", DEBUG状态为:", debug, "(", verdate, ")")

######################################################


# 获取屏幕大小
def getWorkarea():
    monitor_info = GetMonitorInfo(MonitorFromPoint((0, 0)))
    work_area = monitor_info.get("Work")
    return work_area


# 设置窗口位置在屏幕右下角
def setWindowSize(windows, x, y):
    work_area = getWorkarea()
    screenSize_x = work_area[2]
    screenSize_y = work_area[3]
    windowSize_x = x
    windowSize_y = y
    if windows == root:
        windows.set_window_size(windowSize_x, windowSize_y)
        windows.set_display_postion(
            screenSize_x - windowSize_x, screenSize_y - windowSize_y
        )
    print("[DEBUG] 执行了setWindowSize , 参数为：" + str(x) + "," + str(y))


resultHistory = "历史记录：\n"


# 定义获取随机数模块
def 随机数():
    result = random.randint(随机数范围.min, 随机数范围.max)
    # A1

    return result


# 展示抽号窗口
def 创建子窗口(num):
    print("[DEBUG] 执行了创建子窗口")

    随机抽号结果窗口 = tk.Toplevel()

    # 设置字体大小
    width = config.展示窗大小.x
    heigh = config.展示窗大小.y

    min_size = min(width, heigh)
    font_size = min_size // 2  # 根据窗口尺寸计算字体大小
    font_config = ("微软雅黑", font_size)

    # 随机数本体
    label1 = tk.Label(随机抽号结果窗口, text=str(num), font=font_config)

    # 关联窗口大小改变事件，动态调整label的字体大小
    def on_resize(event):
        width = event.width
        height = event.height
        min_size = min(width, height)
        font_size = min_size // 2  # 根据窗口尺寸计算字体大小
        font_config = ("微软雅黑", font_size)
        label1.config(font=font_config)

    随机抽号结果窗口.bind("<Configure>", on_resize)

    # 设置窗体大小
    screenwidth = 随机抽号结果窗口.winfo_screenwidth()
    screenheight = 随机抽号结果窗口.winfo_screenheight()

    随机抽号结果窗口.geometry(
        "%dx%d+%d+%d"
        % (width, heigh, (screenwidth - width) / 2, (screenheight - heigh) / 2)
    )

    # 设置窗口
    随机抽号结果窗口.title("~抽号结果~ (按 X 退出)")
    label1.pack(expand=True, fill=tk.BOTH)
    随机抽号结果窗口.tk.call("tk", "scaling", ScaleFactor / 75)
    setWindowSize(随机抽号结果窗口, config.展示窗大小.x, config.展示窗大小.y)
    随机抽号结果窗口.mainloop()


# 抽号实际部分
def 抽随机号数():
    print("[DEBUG] 执行了抽随机号数")

    ###叶挺部分

    if config.抽两班.enabled == True:
        xuebi = random.randint(1, 2)
        if xuebi == 1:
            classname = "915班的："
            随机数范围.max = 53
        elif xuebi == 2:
            classname = "916班的："
            随机数范围.max = 52
    else:
        classname = ""
    print(classname)
    if config.随机表情.enabled == True:
        bq = random.choice(config.随机表情.bq)
    else:
        bq = ""
    print(bq)
    finalresult = classname + str(随机数()) + bq

    a = random.randint(1, 10)  # lucky dog
    if config.A1.enabled == True and a == 1:
        print("[DEBUG] 进行了 A1")
        finalresult = random.choice(config.A1.num)
    elif (
        config.B1.enabled == True
        and base64.b64encode(finalresult) in config.B1.num_encode
    ):
        print("[DEBUG] 进行了 decode base64")
        抽随机号数()  # try again
    print(finalresult)
    创建子窗口(finalresult)


def 还原函数():
    print("[DEBUG] 执行了还原函数")
    global 随机
    setWindowSize(config.小窗大小.x, config.小窗大小.y)
    # 随机.pack(side=tk.BOTTOM)
    # 还原.pack_forget()


# class DragWindow(tk.Tk):
class DragWindow(tk.Tk):
    print("[DEBUG] 执行了DragWindow类")
    root_x, root_y, abs_x, abs_y = 0, 0, 0, 0
    width, height = None, None

    def __init__(self, topmost=True, alpha=0.6, bg="gray", width=None, height=None):
        super().__init__()
        self["bg"] = bg
        self.width, self.height = width, height
        self.overrideredirect(True)
        self.wm_attributes("-alpha", alpha)  # 透明度
        self.wm_attributes("-toolwindow", True)  # 置为工具窗口
        self.wm_attributes("-topmost", topmost)  # 永远处于顶层
        self.bind("<B1-Motion>", self._on_move)
        self.bind("<ButtonPress-1>", self._on_tap)
        print("[DEBUG] 执行了Dragwindows类初始化")

    def set_display_postion(self, offset_x, offset_y):
        self.geometry("+%s+%s" % (offset_x -config.小窗偏移位置.x, offset_y-config.小窗偏移位置.y))
        print(
            "[DEBUG] 执行了DragWindow类set_display_postion(%s,%s,%s)",
            self,
            offset_x,
            offset_y,
        )

    def set_window_size(self, w, h):
        self.width, self.height = w, h
        self.geometry("%sx%s" % (w, h))
        print("[DEBUG] 执行了DragWindow类set_window_size(%s,%s,%s)", self, w, h)

    def _on_move(self, event):
        offset_x = event.x_root - self.root_x
        offset_y = event.y_root - self.root_y

        if self.width and self.height:
            geo_str = "%sx%s+%s+%s" % (
                self.width,
                self.height,
                self.abs_x + offset_x,
                self.abs_y + offset_y,
            )
        else:
            geo_str = "+%s+%s" % (self.abs_x + offset_x, self.abs_y + offset_y)
        self.geometry(geo_str)
        print("[DEBUG] 执行了DragWindow类_on_move(%s,%s)", self, event)

    def _on_tap(self, event):
        self.root_x, self.root_y = event.x_root, event.y_root
        self.abs_x, self.abs_y = self.winfo_x(), self.winfo_y()
        print("[DEBUG] 执行了DragWindow类_on_tap(%s,%s)", self, event)


root = DragWindow()


setWindowSize(root, config.小窗大小.x, config.小窗大小.y)
label = tk.Label(root, font=('微软雅黑', 10))
label.pack()


def update_label_text():
    label.config(text=getText())
    # 测量标签的最大宽度
    label.update_idletasks()
    label_width = label.winfo_width()
    # 根据标签的最大宽度，调整根窗口的大小
    root.geometry("{}x{}".format(label_width+20, config.小窗大小.y))
    root.after(600000, update_label_text)

def getText():
    encourage = requests.get("https://v1.hitokoto.cn/").json()
    if encourage["from_who"] is None:
        encourage["from_who"] = "None"
    ec = "\"" + encourage["hitokoto"] + "\"\n——" + encourage["from_who"]
    return ec

def quitApp():
    root.destroy()


exit = tk.Button(root, text="Exit", command=quitApp)

exit.pack(side=tk.BOTTOM)
随机 = tk.Button(root, text="随机", command=抽随机号数)
随机.pack(side=tk.BOTTOM)
# text1.pack()


# root.after(1000,小菜单显示内容())
root.tk.call("tk", "scaling", ScaleFactor / 75)

update_label_text()
root.mainloop()
